<?php
ob_start();
require_once('facebook-php-sdk/src/facebook.php');

$app_id = '441699992574659';
$my_url = 'http://www.drawyourheart.com/dyh2013/app.php';

$facebook = new Facebook(array(
'appId'  => $app_id,  //Draw Your Heart App created from apps@heartpreneur.com
'secret' => '4a55ad3815c3259fccb8b0d608a42170',
'fileUpload' => true,
'cookie' => true
));

if(isset($_POST['token']) && isset($_POST['msg'])){
    $access_token = $_POST['token'];    //get access token
    $msg = $_POST['msg'];   //getting the message

    /*$imageData = $_REQUEST['data'];   //get base64 image data as string
    $image = explode('base64,',$imageData);
    $target_path = 'uploadimages/' . md5(date('Ymdgisu')) . '.jpg';
    file_put_contents($target_path, base64_decode($image[1])); //write the file to the location under $target_path */

    //save the drawing image first
    require_once("save_image.php");

    //echo $target_path;

    try {
    // Upload to a user's profile. The photo will be in the
    // first album in the profile. You can also upload to
    // a specific album by using /ALBUM_ID as the path
    //IF everything goes well and the below 4 scenarios are not there , then upload drawing to Wall
    /*
    1) The token expires after expires time (2 hours is the default).
    2) The user changes her password which invalidates the access token.
    3) The user de-authorizes your app.
    4) The user logs out of Facebook.
    */
    $ret_obj = $facebook->api('/me/photos', 'POST', array(
                                 'source' => '@' . $target_path,
                                 'message' => $msg,
                                 'access_token'  => $access_token,
                                 )
                              );
    //echo 'photo_id: ' . $ret_obj['id'];      //return the image path for email to read in the app
    echo 'path:' . $target_path;

    } catch(FacebookApiException $e) {
    // If the user is logged out, you can have a
    // user ID even though the access token is invalid.
    // In this case, we'll get an exception, so we'll
    // just ask the user to login again here.
        //echo "Error type: " . $e->getType() . " || Error message: " . $e->getMessage();
    //for all kinds of OAuthException, we need to login again
            $dialog_url= "https://www.facebook.com/dialog/oauth?"
                    . "client_id=" . $app_id
                    . "&redirect_uri=" . urlencode($my_url); //. "&response_type=code";
                  echo($dialog_url);
    //error_log($e->getType());
    //error_log($e->getMessage());
    }
}
else{
     echo 'Valid Parameters (access token) not passed!';
}
ob_end_flush();
?>